import { fetchAdminList, deleteAdmin, createAdmin, updateAdmin } from '@/services/admin';

export interface AdminModelState {
    list: any[];
    total: number;
    currentPage: number;
    pageSize: number;
    searchParams: any;
}

export default {
    namespace: 'admin',

    state: {
        list: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        searchParams: {},
    },

    effects: {
        *fetchList({ payload }: { payload: any }, { call, put }: { call: Function; put: Function }) {
            const response: { data: { dataSource: any[]; meta: { total: number; page: number; per_page: number } }; } = yield call(fetchAdminList, payload);
            yield put({
                type: 'save',
                payload: {
                    list: response.data.dataSource,
                    total: response.data.meta.total,
                    currentPage: response.data.meta.page,
                    pageSize: response.data.meta.per_page,
                    searchParams: payload,
                },
            });
        },

        *delete({ payload }: { payload: number | number[] }, { call, put }: { call: Function; put: Function }) {
            yield call(deleteAdmin, payload);
            yield put({
                type: 'fetchList',
                payload: {
                    page: 1,
                    pageSize: 10,
                },
            });
        },

        *create({ payload }: { payload: any }, { call, put }: { call: Function; put: Function }) {
            yield call(createAdmin, payload);
            yield put({
                type: 'fetchList',
                payload: {
                    page: 1,
                    pageSize: 10,
                },
            });
        },

        *update({ payload }: { payload: { id: number; data: any } }, { call, put }: { call: Function; put: Function }) {
            yield call(updateAdmin, payload.id, payload.data);
            yield put({
                type: 'fetchList',
                payload: {
                    page: 1,
                    pageSize: 10,
                },
            });
        },
    },

    reducers: {
        save(state: AdminModelState, { payload }: { payload: AdminModelState }) {
            return {
                ...state,
                ...payload,
            };
        },
    },
};